/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-9-22 上午11:39 Created by dwzhang
 */
package com.jade.bss.weixin.api.protocol.xml;

import com.jade.bss.weixin.WeixinException;
import com.jade.framework.base.ErrorConstants;
import com.jade.framework.base.util.HttpUtils;
import com.jade.bss.weixin.WeixinApi;
import com.jade.bss.weixin.WeixinApp;
import org.apache.http.impl.client.CloseableHttpClient;

/**
 * 采用Xml方式的API。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-9-22 上午11:39
 */
public abstract class XmlApi extends WeixinApi
{
    protected <T extends Response> T submitRequest(String url, WeixinApp app, Request request, boolean cert, Class responseClass)
            throws WeixinException
    {
        try {
            if (cert) {
                CloseableHttpClient client = HttpUtils.createP12SSLInsecureClient(app.getCerFilePath(),
                        app.getCerFilePassword());
                return HttpUtils.postXmlHttp(client, url, request, responseClass);
            }
            else {
                return HttpUtils.postXmlHttp(url, request, responseClass);
            }
        }
        catch (Exception e) {
            throw new WeixinException(ErrorConstants.ERR_NETWORK, "http error", e);
        }
    }

    protected void setCommonParam(WeixinApp app, Request request)
    {
        request.setAppId(app.getAppId());
        request.setMchId(app.getMerchantId());
        try {
            request.createSign(app.getApiKey());
        }
        catch (Exception e) {
            e.printStackTrace();

        }
    }
}
